﻿using DataTurnClient.Enum;
using DataTurnClient.Model;
using Newtonsoft.Json;
using Splat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataTurnClient.Server
{
    public class HttpService 
    {
        public static MsgTrun Execute(List<Job> jobList,List<GetSetting> setList, object sender)
        {
            var jobs = jobList.Where(x => x.JobCode == sender.ToString()).FirstOrDefault();
            var service = Locator.Current.GetService<LogService>();
            try
            {
                Post<String> p = new Post<String>();
                string route = jobs.JobRoute.Split(':')[1];
                if (route != null) { route = route + "/"; }
                int line = Convert.ToInt32(jobs.JobRoute.Split(':')[0]);
                GetSetting seting = setList.FirstOrDefault();
                Session session = seting.session.Where(x => x.id == line).FirstOrDefault();
                p.Post_url = $"http://{session.ip}:{session.port}/{session.path}/{route}{sender.ToString()}";
                p.Post_mode = (DType.RequestType)System.Enum.Parse(typeof(DType.RequestType), jobs.JobMode);
                StringBuilder sb = new StringBuilder();
                sb.Append("{}");
                p.Post_data = sb.ToString();
                MsgTrun result = p.PostSend();
                result.Data = sender.ToString() + "-" + JsonConvert.SerializeObject(result);
                jobs.JobRunStatus = Job.JobRunType.Over;
                service.WriterText("auto ", DateTime.Now.ToString("HH-mm-ss") + $"      {jobs.JobCode}" + JsonConvert.SerializeObject(result));
                return result;
            }
            catch (Exception ex)
            {
                MsgTrun result = new MsgTrun
                {
                    Code = 500,
                    Data = sender.ToString() + ex.Message
                };
                jobs.JobRunStatus = Job.JobRunType.Over;
                service.WriterText("auto ", DateTime.Now.ToString("HH-mm-ss") + $"      {jobs.JobCode}" + ex.Message);
                return result;
            }
        }
    }
}
